<template>
  <div class="tag-box">
    <el-tag
      v-for="(item, index) in tagList"
      :key="item.path"
      :closable="index > 0"
      size="medium"
      :disable-transitions="false"
      @click="clickTag(item)"
      @close="closeTag(item)"
      :effect="item.active ? 'dark' : 'plain'"
      >{{ item.title }}</el-tag
    >
  </div>
</template>

<script>
export default {
  data() {
    return {
      tagList: JSON.parse(localStorage.getItem("tagList"))
        ? JSON.parse(localStorage.getItem("tagList"))
        : [],
    };
  },
  mounted() {
    var item = {
      title: this.$route.meta.title,
      path: this.$route.path,
    };
    this.getTag(item);
  },
  beforeDestroy() {
    this.remove();
  },
  watch: {
    $route(to, from) {
      var item = {
        title: to.meta.title,
        path: to.path,
      };
      this.getTag(item);
    },
  },
  methods: {
    skipTag(item) {
      this.$router.push({
        path: item.path,
      });
    },

    getTag(item) {
      var index = this.tagList.map((item) => item.path).indexOf(item.path);
      if (index == -1 && item.title) {
        this.tagList.push({
          path: item.path,
          title: item.title,
          active: false,
        });
      }
      if (this.tagList.length > 10) {
        this.tagList.splice(0, 1);
      }
      this.activeTag(item.path);
      localStorage.setItem("tagList", JSON.stringify(this.tagList));
    },
    remove() {
      localStorage.setItem("tagList", JSON.stringify([]));
    },

    activeTag(path) {
      for (let i in this.tagList) {
        this.tagList[i].active = false;
        if (this.tagList[i].path == path) {
          this.tagList[i].active = true;
        }
      }
    },

    clickTag(item) {
      this.skipTag(item);
    },

    closeTag(item) {
      var index = this.tagList.map((item) => item.path).indexOf(item.path);
      if (item.active) {
        this.skipTag(this.tagList[index - 1]);
      }
      this.tagList.splice(index, 1);
    },
  },
};
</script>

<style lang="less" scoped>
.tag-box {
  width: 100%;
  overflow-x: auto;
  white-space: nowrap;
  .el-tag {
    margin-right: 10px;
    cursor: pointer;
    transition: all 0.3s;
  }
  .el-tag:last-child {
    margin-right: unset;
  }
}
</style>
